import JSEncrypt from 'jsencrypt/bin/jsencrypt.min';
import CryptoJS from 'crypto-js'; // eslint-disable-line

// 密钥对生成 http://web.chacuo.net/netrsakeypair
const publicKey =
  'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK2Fax58GGJXbF47JxmVhiOwPcw3yhsQ\n' +
  '7UMzFLuxQY5ZsdkbwrnCw510Ai6DYey6FpHE5LuYgThzCqa+2oU/9nMCAwEAAQ==';

const privateKey =
  'MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEArYVrHnwYYldsXjsn\n' +
  'GZWGI7A9zDfKGxDtQzMUu7FBjlmx2RvCucLDnXQCLoNh7LoWkcTku5iBOHMKpr7a\n' +
  'hT/2cwIDAQABAkACSET2a69ua7PzMVf8UCkpgwHtE7bG0FwujBdzuIsiMipEDwdr\n' +
  'Xw0vuKaAj+fYrTj2nfAoEVhksWm0HLRHpIwhAiEA4YsK3wIuQbx6brN53rsOz3Yh\n' +
  '2C0glQAnYRUDfiL3bOsCIQDE8/4JnLYyptCGpa6DnXQlTKsiiBUv67s14vv8pvAa\n' +
  'mQIhAKkogInL9+eDtgvK/k+H2k7NGgsppXM7P0231fvHu+zrAiEAupdSILcoYjpq\n' +
  'KnaDLEwawk+tfoygTgMuHPJLu2RI61kCIQCUJzUBHyFGMaMCQKrqpScZLEgUcSfh\n' +
  'aB6EoadMUa26Ow==';

// RSA 加密
export function encrypt(txt) {
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(publicKey); // 设置公钥
  return encryptor.encrypt(txt); // 对数据进行加密
}

// RSA 解密（私钥放在前端不安全，但是【输入框增加对用户可见】需要解密）
export function decrypt(txt) {
  const encryptor = new JSEncrypt();
  encryptor.setPrivateKey(privateKey); // 设置私钥
  return encryptor.decrypt(txt); // 对数据进行解密
}

const aesSecretKey = 'NGQyNjRjMWY2ODNlNGE0ZQ==';
const secretKey = CryptoJS.enc.Base64.parse(aesSecretKey);
// AES 加密
export function encryptAES(value) {
  if (!value) return value;
  const ciphertext = CryptoJS.AES.encrypt(value, secretKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Base64.stringify(ciphertext?.ciphertext);
}

// AES 解密
export function decryptAES(value) {
  if (!value) return value;
  return CryptoJS.AES.decrypt(value, secretKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString(CryptoJS.enc.Utf8);
}
